﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinForm1
{
    public partial class SaveOrUpdataForm : Form
    {
        public SaveOrUpdataForm()
        {
            InitializeComponent();
        }

        public int id;

        public SaveOrUpdataForm(int id , string title , string author)
        {
            InitializeComponent();

            this.id = id;

            txtTitle.Text= title;

            txtAuthor.Text = author;
        }

        //确认
        private void button1_Click(object sender, EventArgs e)
        {
            var title = txtTitle.Text;

            var author = txtAuthor.Text;

            var hasTitle = !string.IsNullOrEmpty(title);

            var hasAuthor = !string.IsNullOrEmpty(author);


            //更新
            if (id > 0)
            {
                if (hasAuthor && hasTitle)
                {
                    var updateSql = string.Format("update Articles set Title='{0}' , Author='{1}'  where Id='{2}' ", title, author, id);

                    var res = DBHelper.AddOrSaveOrDelete(updateSql);

                    if (res == 1)
                    {
                        MessageBox.Show("更新成功", "提示");

                        this.DialogResult = DialogResult.Yes;

                        this.Close();
                    }
                    else
                    {
                        MessageBox.Show("更新失败","提示");
                    }
                }
                else
                {
                    MessageBox.Show("更新不能为空","提示");
                }
            }
            //添加
            else
            {
                if(hasAuthor && hasTitle)
                {
                    var insertSql = string.Format("insert into Articles (Title, Author) values ('{0}','{1}')",title,author);

                    var res = DBHelper.AddOrSaveOrDelete(insertSql);

                    if (res == 1)
                    {
                        MessageBox.Show("添加成功","提示");

                        this.DialogResult = DialogResult.Yes;

                        this.Close();
                    }
                    else
                    {
                        MessageBox.Show("添加失败","提示");
                    }

                }
                else
                {
                    MessageBox.Show("两个都不能为空","提示");
                }
            }
            

        }


        //取消
        private void button3_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.No;

            this.Close();
        }
    }
}
